<template>
  <div class="page-container" v-loading="loading">
    <div class="page-content">
      <div class="panel-container">
        <el-form ref="elForm" :model="formData" :rules="rules" size="mini" label-width="120px">
          <el-row :gutter="100">
            <el-col :span="12">
              <el-form-item label="拍卖名称:" prop="title">
                <el-row>
                  <el-col :span="18">
                    <el-input name="title" v-model="formData.title" type="textarea" autosize placeholder="请输入拍卖名称" clearable :style="{ width: '100%' }"></el-input>
                  </el-col>
                  <el-col :span="5" :offset="1">
                    <el-select v-model="titleType" placeholder="请选择" clearable :style="{ width: '100%' }">
                      <el-option v-for="item in titleTypeList" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                    </el-select>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="100">
            <el-col :span="12">
              <el-form-item label="物资分类:" prop="cate_ids">
                <el-cascader v-model="cateSelected" :options="cateList" collapse-tags :props="{ checkStrictly: true, value: 'num_id', label: 'name', multiple: true }" @change="handleCateChange" clearable></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="100" v-show="keywordList.length > 0 || newMarksList.length > 0">
            <el-col :span="24">
              <el-form-item label="标签:" prop="labels" class="form-keyword">
                <el-checkbox-group v-model="selectedKeywordList" size="mini" id="contentMain">
                  <div v-for="keyword in keywordList" :key="keyword.name">
                    <div style="font-size: 14px">{{ keyword.name }}:</div>
                    <el-checkbox v-for="item in keyword.list" :key="item" :label="item">{{ item }}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="newMarksList.length > 0">
              <el-form-item label="">
                <el-tag v-for="item in newMarksList" :key="item.id" disable-transitions closable style="margin-right: 6px; margin-bottom: 4px" @close="handleTagDelete(item)">
                  {{ item.name }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="100">
            <el-col :span="12">
              <el-form-item label="公司名称:" prop="company_name">
                <el-row>
                  <el-col :span="14">
                    <AutoComplete ref="autoCompleteCompanyName" v-model="formData.company_name" name="company_name" placeholder="请输入公司名称"></AutoComplete>
                    <!-- <el-autocomplete clearable v-model="formData.company_name" :fetch-suggestions="querySearchCompanyName" placeholder="请输入公司名称" @select="handleInputSelect" style="width: 100%"></el-autocomplete> -->
                    <!-- <el-input name="company_name" v-model="formData.company_name" placeholder="请输入公司名称" clearable style="width: 100%"></el-input> -->
                  </el-col>
                  <el-col :span="9" :offset="1">
                    <el-input name="vip_id" v-model="formData.vip_id" placeholder="会员编号(非必填)" clearable style="width: 100%"></el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="信息分类:" prop="msg_type">
                <el-radio-group v-model="msgType" size="mini">
                  <el-radio v-for="item in msgTypeList" :key="item.value" :label="item.label"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="100">
            <el-col :span="12">
              <el-form-item label="所属地区:" prop="city_ids">
                <el-cascader v-model="areaSelected" :options="areaList" :props="{ checkStrictly: true, value: 'code', label: 'name', multiple: true }" @change="handleAreaChange" clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="查看权限:" prop="view_power">
                <el-radio-group v-model="viewPower" size="mini">
                  <el-radio v-for="item in viewPowerList" :key="item.value" :label="item.label"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="100">
            <!-- <el-col :span="12">
              <el-form-item label="报名开始时间:" prop="apply_start_time">
                <el-date-picker v-model="formData.apply_start_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" @paste.native="handlePaste($event, 'apply_start_time')" @change.native="handleChange($event, 'apply_start_time')"> </el-date-picker>
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="公告发布时间:" prop="public_time">
                <el-date-picker v-model="formData.public_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" disabled> </el-date-picker>
                <el-checkbox v-if="editModel === 'edit'" v-model="isUseNow" style="margin-left: 20px">发布时间使用当前时间</el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报名截止时间:" prop="apply_end_time">
                <el-date-picker v-model="formData.apply_end_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" @paste.native="handlePaste($event, 'apply_end_time')" @change.native="handleChange($event, 'apply_end_time')"> </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="起拍价:" prop="start_sell_price">
                <el-input name="start_sell_price" v-model="formData.start_sell_price" type="number" style="width: auto" placeholder="请输入起拍价" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拍卖招标时间:" prop="sell_time">
                <el-date-picker v-model="formData.sell_time" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" @change="handleSellTimeChange" @paste.native="handlePaste($event, 'sell_time')" @change.native="handleChange($event, 'sell_time')"> </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保证金:" prop="promise_price">
                <div class="panel-line">
                  <el-input name="promise_price" v-model="formData.promise_price" type="number" style="width: auto" placeholder="请输入保证金" clearable></el-input>
                  <el-select v-model="formData.promise_unit" placeholder="单位" clearable style="width: 70px; margin-left: 10px">
                    <el-option v-for="item in promiseUnitList" :key="item.value" :value="item.value" :label="item.label"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人:" prop="user_name">
                <AutoComplete ref="autoCompleteUserName" v-model="formData.user_name" name="user_name" placeholder="请输入联系人"></AutoComplete>
                <!-- <el-autocomplete clearable v-model="formData.user_name" :fetch-suggestions="querySearchUserName" placeholder="请输入联系人" @select="handleInputSelect"></el-autocomplete> -->
                <!-- <el-input autocomplete="on" name="user_name" v-model="formData.user_name" placeholder="请输入联系人" clearable style="width: auto"></el-input> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="评估价:" prop="evaluation">
                <el-select v-model="formData.evaluation" placeholder="请选择" clearable>
                  <el-option v-for="item in evaluationList" :key="item.value" :value="item.value" :label="item.key"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话:" prop="user_phone">
                <AutoComplete ref="autoCompleteUserPhone" v-model="formData.user_phone" name="user_phone" placeholder="请输入联系电话"></AutoComplete>
                <!-- <el-autocomplete clearable v-model="formData.user_phone" :fetch-suggestions="querySearchUserPhone" placeholder="请输入联系电话" @select="handleInputSelect" style="width: 100%"></el-autocomplete> -->
                <!-- <el-input autocomplete="on" name="user_phone" v-model="formData.user_phone" placeholder="请输入联系电话" style="width: 100%" clearable></el-input> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="拍卖方式:" prop="sell_type">
                <el-radio-group v-model="sellType" size="mini">
                  <el-radio v-for="item in sellTypeList" :key="item.value" :label="item.label"></el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="源网址:" prop="source_url">
                <el-row>
                  <el-col :span="12">
                    <el-input name="source_url" v-model="formData.source_url" placeholder="请输入源网址" clearable :style="{ width: '100%' }"></el-input>
                  </el-col>
                  <el-col :span="4" style="margin-left: 10px">
                    <el-button type="text" size="mini" @click="handleLink">访问</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="判断依据:" prop="do_reason">
                <el-input autocomplete="on" name="do_reason" v-model="formData.do_reason" placeholder="请输入判断依据" style="width: 100%" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="公告图片:" prop="images">
                <ImageDraggable ref="imageDraggable" infoType="notice" @change="handleImagesChange" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="信息介绍:" prop="desc">
                <TinyMCE ref="tinymce" v-model="formData.desc" :height="800" infoType="notice" :key="'noticePublish' + tinymceFlag" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="CRM关键词:" prop="key_words">
                <el-row>
                  <el-col :span="12">
                    <el-input name="key_words" v-model="formData.key_words" placeholder="请输入CRM关键词" clearable :style="{ width: '100%' }"></el-input>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="原文链接:">
                <el-row>
                  <el-col :span="12">
                    <el-input name="paper_url" v-model="formData.paper_url" placeholder="请输入原文链接" clearable :style="{ width: '100%' }"></el-input>
                  </el-col>
                </el-row>
                <!-- <a :href="detail.paper_url" class="link" target="_blank" v-if="detail.paper_url">
                  {{ detail.paper_url }}
                </a> -->
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="附件:">
                <FileUpload ref="FileUpload" @change="handleFileChange" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="fixed-container">
      <div class="fixed-content">
        <div class="panel-container">
          <div class="panel-content" v-if="editModel === 'add'">
            <el-button size="mini" @click="handleClose">取消</el-button>
            <!-- <el-button size="mini" type="primary" @click="handleSubmit">发布</el-button> -->
            <el-button size="mini" type="primary" @click="handleSubmit('next')">发布</el-button>
          </div>
          <div class="panel-content" v-if="editModel === 'edit'">
            <el-button size="mini" @click="handleClose">取消</el-button>
            <el-button size="mini" type="warning" @click="handleLinkPage" v-if="detail.sts === 1 || detail.sts === 2 || detail.sts === 3">访问页面</el-button>
            <el-button size="mini" type="danger" @click="handleDelete" v-if="detail.sts !== 5">删除</el-button>
            <!-- 2024/11/18 去掉恢复功能 -->
            <!-- <el-button size="mini" type="warning" @click="handleBack" v-else>放弃修改并恢复</el-button> -->
            <el-button size="mini" type="primary" @click="handleSubmit">发布</el-button>
            <!-- <el-button size="mini" type="primary" @click="handleSubmit('next')" v-else>发布</el-button> -->
          </div>
        </div>
      </div>
    </div>

    <!--  确认 -->
    <el-dialog title="请确认信息填写无误" :visible.sync="showDialogConfirm">
      <DialogConfirm v-if="showDialogConfirm" :info="formData" :selectedAreaList="selectedAreaList" :selectedCateList="selectedCateList" :promiseUnitList="promiseUnitList" @close="showDialogConfirm = false" @confirm="handleConfirm" />
    </el-dialog>
  </div>
</template>
<script>
import { apiAssetKeyWords, apiGetAllLabel } from '@/api/assetsPublic'
import { apiNoticeSelect, apiNoticeAdd, apiNoticeDetail, apiNoticeEdit, apiNoticeEditGetNext, apiNoticeDel, apiNoticeBack } from '@/api/biddingNotice'
import ImageDraggable from '@/components/audio/ImageDraggable.vue'
import FileUpload from '@/components/audio/FileUpload.vue'
import DialogConfirm from './components/DialogConfirm.vue'
import AutoComplete from './components/AutoComplete.vue'
import { isMobile } from '@/utils/validate'
import { formatDate } from '@/utils/index'
import TinyMCE from '@/components/TinyMCE7'

export default {
  name: 'NoticePublish',
  components: { ImageDraggable, FileUpload, DialogConfirm, TinyMCE, AutoComplete },
  props: [],
  data() {
    let validaMobile = (rule, value, callback) => {
      const splitList = [',', '，', '、', '/', '\\']
      const phoneReg = /^((\d+)-)(\d+)(-(\d+))?$/
      const phoneText = /[\u4e00-\u9fa5]+/
      let flag = false

      // 把不间断空格替换成空格
      let newvalue = value
        .split('')
        .map((c) => {
          if (c.charCodeAt(0) === 160) {
            return ' '
          } else {
            return c
          }
        })
        .join('')

      // 把分隔符替换成空格
      splitList.forEach((split) => {
        newvalue = newvalue.replaceAll(split, ' ')
      })
      newvalue.split(' ').forEach((item) => {
        let str = item.replace(/\s/g, '')
        if (str && !phoneReg.test(str) && !isMobile(str) && !phoneText.test(str)) {
          flag = true
        }
      })

      if (flag) {
        callback(new Error('电话号格式错误'))
      } else {
        this.formData.user_phone = newvalue
          .split(' ')
          .filter((item) => !!item)
          .join(' ')
        callback()
      }
    }
    let validaDate = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if ((this.editModel === 'add' || (this.editModel === 'edit' && this.formData.public_time === '')) && new Date(value) <= new Date()) {
        callback(new Error('报名截止时间不能早于或等于当前时间'))
        // } else if (this.formData.apply_start_time && new Date(value) <= new Date(this.formData.apply_start_time)) {
        //   callback(new Error('报名截止时间不能早于或等于报名开始时间'))
      } else if (this.formData.public_time && new Date(value) <= new Date(this.formData.public_time)) {
        callback(new Error('报名截止时间不能早于或等于公告发布时间'))
      } else {
        callback()
      }
    }
    let validaDate2 = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if ((this.editModel === 'add' || (this.editModel === 'edit' && this.formData.public_time === '')) && new Date(value) <= new Date()) {
        callback(new Error('拍卖招标时间不能早于或等于当前时间'))
        // } else if (this.formData.apply_start_time && new Date(value) <= new Date(this.formData.apply_start_time)) {
        //   callback(new Error('拍卖招标时间不能早于或等于报名开始时间'))
      } else if (this.formData.public_time && new Date(value) <= new Date(this.formData.public_time)) {
        callback(new Error('拍卖招标时间不能早于或等于公告发布时间'))
      } else {
        callback()
      }
    }
    let validaSellType = (rule, value, callback) => {
      if (value === 0 || value === '0') {
        callback(new Error('请选择拍卖方式'))
      } else {
        callback()
      }
    }

    return {
      showDialogConfirm: false,
      tinymceFlag: 1,
      queryId: '',
      tableQuery: {},
      loading: false,
      editModel: 'add',
      formData: {
        title: '',
        title_type: 0,
        desc: '',
        company_name: '',
        key_words: '',
        msg_type: '',
        images: '',
        apply_start_time: '',
        apply_end_time: '',
        public_time: '',
        sell_time: '',
        user_name: '',
        user_phone: '',
        start_sell_price: '',
        promise_price: '',
        promise_unit: 1,
        evaluation: '',
        paper_url: '',
        source_url: '',
        files: '',
        vip_id: '',
        labels: '',
        view_power: 1,
        cate_ids: '',
        city_ids: '',
        new_marks: '',
        is_use_now: 0,
        sell_type: '',
        do_reason: '',
      },
      rules: {
        title: [{ required: true, message: '请输入拍卖名称', trigger: 'blur' }],
        cate_ids: [{ required: true, message: '请选择物资分类', trigger: 'change' }],
        company_name: [{ required: true, message: '请输入公司名称', trigger: 'change' }],
        msg_type: [{ required: true, message: '请选择信息分类', trigger: 'blur' }],
        sell_type: [
          { required: true, message: '请选择拍卖方式', trigger: 'blur' },
          { validator: validaSellType, trigger: 'blur' },
        ],
        view_power: [{ required: true, message: '请选择', trigger: 'blur' }],
        city_ids: [{ required: true, message: '请选择所属地区', trigger: 'change' }],
        user_phone: [
          { required: true, message: '请输入发布人手机号', trigger: 'change' },
          { validator: validaMobile, trigger: 'blur' },
        ],
        apply_end_time: [{ validator: validaDate, trigger: 'blur' }],
        sell_time: [{ validator: validaDate2, trigger: 'blur' }],
        desc: [{ required: true, message: '请输入信息介绍', trigger: 'blur' }],
      },
      detail: {},
      // 临时变量
      titleType: '',
      msgType: '',
      sellType: '',
      viewPower: '付费会员',
      cateSelected: '',
      areaSelected: '',
      selectedKeywordList: [],
      isUseNow: false,
      keywordList: [],
      newMarksList: [],
      pubTimeCopy: '',
      // 下拉数据
      cateList: [],
      areaList: [],
      evaluationList: [],
      titleTypeList: [
        { label: '变更', value: 1 },
        { label: '延期', value: 2 },
        { label: '暂停', value: 5 },
        { label: '终止', value: 3 },
        { label: '澄清', value: 4 },
      ],
      msgTypeList: [
        { label: '拍卖', value: 1 },
        { label: '招标', value: 2 },
      ],
      sellTypeList: [
        { label: '网络拍卖', value: 1 },
        { label: '现场拍卖', value: 2 },
        { label: '其他', value: 3 },
      ],
      viewPowerList: [
        { label: '付费会员', value: 1 },
        { label: '注册会员', value: 2 },
      ],
      promiseUnitList: [
        { label: '万', value: 1 },
        { label: '元', value: 2 },
      ],
      oldAreaList: [],
      oldArea: '',
      submitType: '',
      selectedAreaList: '',
      selectedCateList: '',
      fileList: [],
    }
  },
  computed: {},
  watch: {
    'formData.title': {
      handler(value) {
        this.findInPage(value)
      },
      immediate: true,
    },
    selectedKeywordList: {
      handler() {
        this.formData.labels = this.selectedKeywordList
      },
      immediate: true,
    },
    newMarksList: {
      handler() {
        this.formData.new_marks = this.newMarksList.map((item) => JSON.stringify(item)).join('|')
      },
      immediate: true,
    },
    msgType: {
      handler(val) {
        if (val) {
          this.formData.msg_type = this.msgTypeList.find((item) => item.label === val).value
        }
      },
      immediate: true,
    },
    sellType: {
      handler(val) {
        if (val) {
          this.formData.sell_type = this.sellTypeList.find((item) => item.label === val).value
        }
      },
      immediate: true,
    },
    viewPower: {
      handler(val) {
        this.formData.view_power = this.viewPowerList.find((item) => item.label === val).value
      },
      immediate: true,
    },
    isUseNow() {
      if (this.isUseNow) {
        this.formData.is_use_now = 1
        this.formData.public_time = new Date()
      } else {
        this.formData.is_use_now = 0
        this.formData.public_time = this.pubTimeCopy
      }
    },
    titleType() {
      if (this.titleType === '') {
        this.formData.title_type = 0
      } else {
        this.formData.title_type = this.titleType
      }
    },
  },
  activated() {
    this.tinymceFlag++
  },
  mounted() {
    this.init()
  },
  methods: {
    // 初始化
    init() {
      this.getSelectList().then(() => {
        this.queryId = this.$route.query.id
        if (this.queryId) {
          this.editModel = 'edit'
          const tableQuery = window.localStorage.getItem('notice-edit-table-query')
          if (tableQuery) {
            this.tableQuery = JSON.parse(tableQuery)
            this.tableQuery.position++
            this.tableQuery.is_next = 1
          } else {
            this.tableQuery = {}
            this.tableQuery.position = 1
            this.tableQuery.is_next = 1
          }
          this.getDetail()
        } else {
          this.editModel = 'add'
          // 报名开始，公告发布时间默认今天
          // this.formData.apply_start_time = formatDate(new Date())
          this.formData.public_time = formatDate(new Date())
        }
      })
    },
    // 获取详情
    getDetail() {
      this.loading = true
      apiNoticeDetail({ id: this.queryId })
        .then((res) => {
          this.loading = false
          this.setDetail(res.data)
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取下一条详情
    getNextDetail() {
      this.loading = true
      apiNoticeEditGetNext(this.tableQuery)
        .then((res) => {
          this.loading = false
          this.resetForm()
          this.setDetail(res.data)
          this.tableQuery.position++
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 设置详情数据
    setDetail(data) {
      this.detail = data
      for (let key in this.formData) {
        if (key === 'new_marks') {
          this.newMarksList = data.new_marks
        } else if (data[key] !== null) {
          this.formData[key] = data[key]
        }
      }
      this.handleSellTimeChange(this.formData.sell_time)
      this.formData.id = data.id
      if (data.cate_ids) {
        this.cateSelected = data.cate_ids
        this.formData.cate_ids = data.cate_ids.join('|')
      } else {
        this.cateSelected = []
        this.formData.cate_ids = ''
      }
      if (data.city_ids) {
        this.areaSelected = data.city_ids
        this.formData.city_ids = data.city_ids.join('|')
        this.handleAreaChange(data.city_ids)
      } else {
        this.areaSelected = []
        this.formData.city_ids = ''
      }
      let keywordList = []
      if (this.formData.labels) {
        keywordList = this.formData.labels.split(',')
      }
      this.handleCateChange(this.cateSelected).then((res) => {
        this.selectedKeywordList = keywordList
      })
      this.titleType = this.formData.title_type === 0 ? '' : this.formData.title_type
      this.formData.is_use_now = 0
      if (this.formData.public_time === '') {
        this.formData.public_time = formatDate(new Date())
      }
      this.pubTimeCopy = this.formData.public_time
      this.msgType = this.msgTypeList.find((item) => item.value === this.formData.msg_type)?.label
      this.sellType = this.sellTypeList.find((item) => item.value === this.formData.sell_type)?.label
      this.viewPower = this.viewPowerList.find((item) => item.value === this.formData.view_power)?.label
      this.$refs.imageDraggable.setValue(this.formData.images)
      this.$refs.FileUpload.setValue(this.formData.files)
      this.$refs.tinymce.setValue(this.formData.desc)
    },
    // 获取下拉数据
    getSelectList() {
      return Promise.all([apiNoticeSelect(), this.$store.dispatch('select/getNoticeCateList'), this.$store.dispatch('select/getCityList')]).then((res) => {
        const { evaluation } = res[0]
        this.evaluationList = evaluation
        this.cateList = res[1]
        this.areaList = res[2]
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.cateSelected = this.areaSelected = []
      this.selectedKeywordList = this.keywordList = this.newMarksList = []
      this.msgType = ''
      this.sellType = ''
      this.viewPower = '付费会员'
      this.$refs.imageDraggable.reset()
      this.$refs.FileUpload.reset()
      this.$refs.tinymce.reset()
      if (this.editModel === 'edit') {
        this.formData.id = ''
      }
      this.isUseNow = false
      this.oldAreaList = []
      this.oldArea = ''
      this.submitType = ''
      this.selectedAreaList = ''
      this.selectedCateList = ''
      this.fileList = []
      this.titleType = ''
      this.formData.vip_id = ''
      this.formData.paper_url = ''
    },
    // 删除标签
    handleTagDelete(item) {
      this.newMarksList = this.newMarksList.filter((item1) => item1.id !== item.id)
    },
    // 获取系统自动打标签
    getAllLabel() {
      return new Promise((resolve, reject) => {
        apiGetAllLabel({
          title: this.formData.title,
          content: '',
          c1: this.cateSelected[0][0],
        })
          .then((res) => {
            this.newMarksList = res.data
            resolve()
          })
          .catch(() => {
            reject()
          })
      })
    },
    // 提交
    handleSubmit(type) {
      console.log(this.formData)
      this.submitType = type
      this.$refs['elForm'].validate((valid, message) => {
        if (!valid) {
          const name = Object.keys(message)[0]
          this.$message.error(message[name][0].message)
          this.$nextTick(() => {
            const el = document.querySelectorAll('.el-form-item__error')[0]
            el.scrollIntoView({ block: 'center', behavior: 'smooth' })
          })
          return
        }
        if (this.fileList.find((item) => item.status === 'ready')) {
          this.$confirm('还有附件未上传完毕，是否确认发布？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.formData.files = this.fileList
              .map((item) => {
                return item.url || item.response
              })
              .join('|')
            this.showDialogConfirm = true
          })
        } else {
          this.formData.files = this.fileList
            .map((item) => {
              return item.url || item.response
            })
            .join('|')
          this.showDialogConfirm = true
        }
      })
    },
    handleConfirm() {
      this.showDialogConfirm = false
      this.loading = true
      this.clearTimeNull()
      this.setQuerySearch()
      if (this.editModel === 'add') {
        this.getAllLabel()
          .then(() => {
            apiNoticeAdd(this.formData)
              .then((res) => {
                this.loading = false
                this.$message({
                  message: '发布成功',
                  type: 'success',
                })
                setTimeout(() => {
                  if (this.submitType === 'next') {
                    this.resetForm()
                    // 报名开始，默认今天
                    // this.formData.apply_start_time = formatDate(new Date())
                    this.formData.public_time = formatDate(new Date())
                    window.scrollTo({ top: 0 })
                  } else {
                    this.handleClose()
                  }
                }, 1000)
              })
              .catch(() => {
                this.loading = false
              })
          })
          .catch(() => {
            this.loading = false
          })
      } else if (this.editModel === 'edit') {
        apiNoticeEdit(this.formData)
          .then((res) => {
            this.loading = false
            this.$message({
              message: '发布成功',
              type: 'success',
            })
            setTimeout(() => {
              if (this.submitType === 'next') {
                this.getNextDetail()
                window.scrollTo({ top: 0 })
              } else {
                this.handleClose()
              }
            }, 1000)
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    // 取消
    handleClose() {
      if (this.editModel === 'edit') {
        window.close()
      } else {
        this.$bus.$emit('noticeListUpdate')
        this.$bus.$emit('closeSelectedTag', this.$route)
      }
    },
    // 访问页面
    handleLinkPage() {
      window.open(`https://www.feijiu.net/gonggao/${this.detail.number_id}.html`)
    },
    // 删除
    handleDelete() {
      window.enterPreventDefault = false
      this.$confirm('确认要删除这条信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          window.enterPreventDefault = true
          apiNoticeDel({ ids: [this.formData.id] }).then(() => {
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            setTimeout(() => {
              this.handleClose()
            }, 1000)
          })
        })
        .catch(() => {
          window.enterPreventDefault = true
        })
    },
    // 恢复
    // <!-- 2024/11/18 去掉恢复功能 -->
    handleBack() {
      window.enterPreventDefault = false
      this.$confirm('确认回退到待处理状态吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          window.enterPreventDefault = true
          apiNoticeBack({ ids: [this.formData.id] }).then(() => {
            this.$message({
              type: 'success',
              message: '操作成功!',
            })
            setTimeout(() => {
              this.handleClose()
            }, 1000)
          })
        })
        .catch(() => {
          window.enterPreventDefault = true
        })
    },
    // 访问
    handleLink() {
      if (this.formData.source_url) {
        window.open(this.formData.source_url)
      }
    },
    // 清除时间null
    clearTimeNull() {
      // let list = ['apply_start_time', 'apply_end_time', 'public_time', 'sell_time']
      let list = ['apply_end_time', 'public_time', 'sell_time']
      list.forEach((item) => {
        if (this.formData[item] === null) {
          this.formData[item] = ''
        }
      })
    },
    // 图片变动
    handleImagesChange(value) {
      this.formData.images = value
        .filter((item) => item.status === 'success')
        .map((item) => item.onlineUrl)
        .join('|')
    },
    // 选择地区
    handleAreaChange(value) {
      // 把上级和下级都删掉
      if (value.length > 1 && value.length > this.oldAreaList.length) {
        let list = [...value]
        let deleteUpLevel = list.map((item) => {
          return {
            value: item,
            delete: false,
          }
        })
        const currentValue = this.getNewArea(value, this.oldAreaList)
        if (currentValue) {
          const currentLength = currentValue.length
          deleteUpLevel.forEach((item) => {
            let minLength = Math.min(item.value.length, currentLength)
            if (item.value.length !== currentLength && this.arrayEqual(currentValue.slice(0, minLength), item.value.slice(0, minLength))) {
              item.delete = true
            }
          })
          this.areaSelected = deleteUpLevel.filter((item) => !item.delete).map((item) => item.value)
        }
      }
      this.oldAreaList = this.areaSelected
      this.formData.city_ids = this.areaSelected.join('|')
      this.formatTitle()
    },
    // 数组判断是否相等
    arrayEqual(val1, val2) {
      return JSON.stringify(val1) === JSON.stringify(val2)
    },
    // 获取新增的地区
    getNewArea(newList, oldList) {
      let newVal = null
      newList.forEach((item) => {
        let flag = true
        oldList.forEach((item2) => {
          if (this.arrayEqual(item, item2)) {
            flag = false
          }
        })
        if (flag) {
          newVal = item
        }
      })
      return newVal
    },
    // 附件变动
    handleFileChange(value) {
      this.fileList = value
    },
    // 选择分类
    handleCateChange(value) {
      return new Promise((resolve) => {
        this.formData.cate_ids = value.join('|')
        this.selectedKeywordList = []
        this.keywordList = []
        this.selectedCateList = ''
        value.forEach((item) => {
          if (item && item.length > 0) {
            // 获取分类标签
            const length = item.length
            const cate_id = item[length - 1]
            let cateName = ''
            // 获取分类文字
            const cate1 = this.cateList.find((item1) => item1.num_id === item[0])
            this.selectedCateList += cate1.name
            cateName = cate1.name
            if (item[1]) {
              const cate2 = cate1.children.find((item1) => item1.num_id === item[1])
              this.selectedCateList += '-' + cate2.name
              cateName += '-' + cate2.name
            }
            this.selectedCateList += ' '

            apiAssetKeyWords({
              cate_id,
              level: item.length === 1 ? 1 : 2,
              info_type: 2,
            }).then((res) => {
              if (res.data.length > 0) {
                this.keywordList.push({ name: cateName, list: res.data })
                this.$nextTick(() => {
                  this.findInPage(this.formData.title)
                })
              }

              resolve()
            })
          } else {
            resolve()
          }
        })
      })
    },
    // 招标拍卖时间变动
    handleSellTimeChange(value) {
      this.formatTitle()
    },
    // 格式化标题，添加日期和地区
    formatTitle() {
      // 新地区
      let newArea = ''
      this.areaSelected &&
        this.areaSelected.forEach((item) => {
          let area = ''
          let shengItem, shiItem, quItem
          shengItem = this.areaList.find((sheng) => sheng.code === item[0])
          area += shengItem.name
          if (item[1]) {
            shiItem = shengItem.children.find((shi) => shi.code === item[1])
            area += shiItem.name
          }
          if (item[2]) {
            quItem = shiItem.children.find((qu) => qu.code === item[2])
            area += quItem.name
          }
          if (newArea.length === 0) {
            newArea += area
          } else {
            newArea += ' ' + area
          }
        })
      this.selectedAreaList = newArea

      // 新日期
      let newDate = ``
      if (this.formData.sell_time) {
        const month = this.formData.sell_time.split(' ')[0].split('-')[1]
        const date = this.formData.sell_time.split(' ')[0].split('-')[2]
        newDate = `${month}月${date}日`
      }
      // 标题添加地区
      // 去掉原标题中的地区
      let titleCopy = this.formData.title
      let titlePrefix = ''
      let titleDate = ''
      let titleContent = ''
      let titleArea = ''

      // 标题前缀 (网络报名)|(邮箱报名)|(现场报名)|(预告)|(变更)|(延期)|(暂停)|(终止)|(澄清)
      let reg0 = /^((\(|\uFF08)(\u7f51\u7edc\u62a5\u540d|\u90ae\u7bb1\u62a5\u540d|\u73b0\u573a\u62a5\u540d|\u9884\u544a|\u53d8\u66f4|\u5ef6\u671f|\u6682\u505c|\u7ec8\u6b62|\u6f84\u6e05)(\uFF09|\)))+/
      if (titleCopy.match(reg0)) {
        titlePrefix = titleCopy.match(reg0)[0]
        titleCopy = titleCopy.replace(reg0, '')
      }
      // 标题日期
      if (titleCopy.match(/^\d{1,2}月\d{1,2}日/)) {
        titleDate = titleCopy.match(/^\d{1,2}月\d{1,2}日/)[0]
        titleCopy = titleCopy.replace(/^\d{1,2}月\d{1,2}日/, '')
      }
      // 标题地区-变动-单个地区
      let reg1 = new RegExp('^' + this.oldArea)
      if (titleCopy.match(reg1)) {
        titleArea = titleCopy.match(reg1)[0]
        titleCopy = titleCopy.replace(reg1, '')
      }
      // 标题地区-初始化-单个地区
      let reg = new RegExp('^' + newArea)
      if (titleCopy.match(reg)) {
        titleArea = titleCopy.match(reg)[0]
        titleCopy = titleCopy.replace(reg, '')
      }
      // 标题地区-变动-多个地区
      let reg3 = new RegExp('\\(' + this.oldArea + '\\)')
      if (titleCopy.match(reg3)) {
        titleArea = titleCopy.match(reg3)[0]
        titleCopy = titleCopy.replace(reg3, '')
      }
      // 标题地区-初始化-多个地区
      let reg2 = new RegExp('\\(' + newArea + '\\)')
      if (titleCopy.match(reg2)) {
        titleArea = titleCopy.match(reg2)[0]
        titleCopy = titleCopy.replace(reg2, '')
      }
      // 标题内容
      titleContent = titleCopy

      this.oldArea = newArea
      if (newArea) {
        if (this.areaSelected.length === 1) {
          // 单个地区拼在日期后面
          this.formData.title = titlePrefix + newDate + newArea + titleContent
        } else {
          // 多个日期拼在标题最后
          this.formData.title = titlePrefix + newDate + titleContent + '(' + newArea + ')'
        }
      } else {
        this.formData.title = titlePrefix + newDate + titleContent
      }
    },
    // 格式化粘贴时间
    formatTime(time) {
      const regex = /\d+/g
      const numList = time.match(regex)
      // 至少有一个年份，后面的可以补0
      if (numList && numList.length > 0) {
        const list = ['0000', '01', '01', '00', '00', '00']
        if (numList[0].length > 4) {
          // 处理yyyyMMddHHmmss
          list[0] = numList[0].slice(0, 4)
          list[1] = numList[0].slice(4, 6)
          list[2] = numList[0].slice(6, 8)
          list[3] = numList[0].slice(8, 10)
          list[4] = numList[0].slice(10, 12)
          list[5] = numList[0].slice(12, 14)
        } else {
          for (let i = 0; i < 6; i++) {
            if (numList[i]) {
              list[i] = numList[i]
            }
          }
        }

        let string = `${list[0]}-${list[1]}-${list[2]} ${list[3]}:${list[4]}:${list[5]}`
        if ((time.includes('下午') || time.includes('PM')) && list[3] < 12) {
          string += ' PM'
        }
        let date = new Date(string)
        if (isNaN(date.getTime()) || date.getTime() < 0) {
          return {
            date: false,
            value: time,
          }
        } else {
          return {
            date: true,
            value: formatDate(date),
          }
        }
      } else {
        return {
          date: false,
          value: time,
        }
      }
    },
    // 粘贴时间
    handlePaste(event, model) {
      var clipboardData, pastedData
      clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData.types && clipboardData.types.length) {
        if (clipboardData.types.includes('text/plain')) {
          pastedData = clipboardData.getData('Text')
          const result = this.formatTime(pastedData)
          if (result.date) {
            event.preventDefault()
            this.formData[model] = result.value
          }
        }
      }
    },
    // 时间变动，格式化时间
    handleChange(event, model) {
      const result = this.formatTime(event.target.value)
      if (result.date) {
        this.formData[model] = result.value
      }
    },
    // 标题中的词语在标签中高亮显示，两个字及以上
    findInPage(searchText) {
      let $labelList = $('.form-keyword .el-checkbox__label')
      $labelList.each((index, ele) => {
        const content = $(ele).html()
        var newHtml = content.replaceAll('<b class="highlight">', '')
        var newHtml = newHtml.replaceAll('</b>', '')
        $(ele).html(newHtml)
      })
      if (searchText.length === 0) {
        return
      }

      $labelList.each((index, ele) => {
        const content = $(ele).text()
        let newHtml = content
        const matches = this.getCommonPart(searchText, content)
        let matchesList = matches.map((item) => {
          return {
            value: item,
            index: content.indexOf(item),
          }
        })
        let temp = []
        matchesList.forEach((item, index) => {
          if (index === 0) {
            temp.push(item.value)
          } else {
            if (item.index === matchesList[index - 1].index + 1) {
              // 说明位置在一起
              temp.push(item.value)
            } else {
              if (temp.length >= 2) {
                const highlight = temp.join('')
                newHtml = newHtml.replace(highlight, '<b class="highlight">' + highlight + '</b>')
              }
              temp = []
              temp.push(item.value)
            }
          }
        })
        if (temp.length >= 2) {
          const highlight = temp.join('')
          newHtml = newHtml.replace(highlight, '<b class="highlight">' + highlight + '</b>')
        }
        $(ele).html(newHtml)
      })
    },
    // 获取两个字符串个相同的部分
    getCommonPart(str1, str2) {
      const regex = new RegExp(`[${str2}]`, 'g')
      const matches = str1.match(regex) || []
      return matches
    },
    // 保存输入纪录
    setQuerySearch() {
      this.$refs.autoCompleteCompanyName.setQuerySearchItem()
      this.$refs.autoCompleteUserName.setQuerySearchItem()
      this.$refs.autoCompleteUserPhone.setQuerySearchItem()
    },
  },
}
</script>
<style lang="scss" scoped>
.el-upload__tip {
  line-height: 1.2;
}
.panel-container {
  padding-bottom: 70px;
  background: #e5eef5;
}
.fixed-container {
  position: fixed;
  right: 0;
  bottom: 0;
  width: calc(100% - 140px);
  z-index: 100;
  padding: 0 10px;
  .panel-container {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    padding: 6px;
    margin: 0;
  }
}
.panel-content {
  display: flex;
  justify-content: center;
  align-items: center;
}
.form-keyword .el-checkbox {
  width: 170px;
  margin-right: 0px;
}
::v-deep b.highlight {
  font-weight: normal;
  background: yellow;
}
.el-button + .el-button {
  margin-left: 60px;
}
</style>
